package com.eii.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.eii.common.constant.BusinessTypeConstants;
import com.eii.common.web.controller.BaseController;
import com.eii.common.web.domain.Result;
import com.eii.common.web.page.PageResult;
import com.eii.excel.util.ExcelUtils;
import com.eii.log.annotation.AuditLog;
import com.eii.oauth2.common.annotation.InnerAuth;
import com.eii.oauth2.common.annotation.RequiresPermissions;
import com.eii.system.api.domain.SysOperLog;
import com.eii.system.controller.vo.SysOperLogExcel;
import com.eii.system.service.ISysOperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 操作日志记录
 */
@RestController
@RequestMapping("/operlog")
public class SysOperlogController extends BaseController {

    private final static String CONTROLLER_TITLE = "操作日志";

    @Autowired
    private ISysOperLogService operLogService;

    @RequiresPermissions("system:operlog:list")
    @GetMapping("/list")
    public PageResult list(SysOperLog operLog) {
        startPage();
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        return getPageResult(list);
    }

    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.EXPORT)
    @RequiresPermissions("system:operlog:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOperLog operLog) throws IOException {
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        List<SysOperLogExcel> sysOperLogExcels = BeanUtil.copyToList(list, SysOperLogExcel.class);
        String datestr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String filename = "操作日志" + datestr + ".xlsx";
        ExcelUtils.exportExcelStream(response, filename, SysOperLogExcel.class, sysOperLogExcels);
    }

    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.DELETE)
    @RequiresPermissions("system:operlog:remove")
    @DeleteMapping("/{operIds}")
    public Result remove(@PathVariable Long[] operIds) {
        return toResult(operLogService.deleteOperLogByIds(operIds));
    }

    @RequiresPermissions("system:operlog:remove")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.CLEAN)
    @DeleteMapping("/clean")
    public Result clean() {
        operLogService.cleanOperLog();
        return Result.success();
    }

    @InnerAuth
    @PostMapping
    public Result add(@RequestBody SysOperLog operLog) {
        return toResult(operLogService.insertOperlog(operLog));
    }
}
